/**
 * 
 */
package com.xbang.core.web.interceptor;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author dev.zhang
 */
public class SearchCriteriaCleanupInterceptor extends AbstractInterceptor {

	private static final Log logger = LogFactory.getLog(SearchCriteriaCleanupInterceptor.class);

	private static final List<String> CLEANUP_URL = Arrays.asList(new String[] {});

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (shouldCleanup(request)) {
			HttpSession session = request.getSession();

			// clear up all the search criteria in httpSession
			if (session.getAttribute("searchCriteriaList") != null) {
				List<String> criteriaList = (List<String>) session.getAttribute("searchCriteriaList");
				if (criteriaList != null) {
					for (int index = 0; index < criteriaList.size(); index++) {
						session.removeAttribute(criteriaList.get(index));
					}
				}
			}

			// clear up all the conversation information in httpSession
			// if(session.getAttribute(ScopeType.CONVERSATION.toString()) != null) {
			// session.removeAttribute(ScopeType.CONVERSATION.toString());
			// }

		}
		return invocation.invoke();
	}

	/**
	 * Determine whether the the url should clean up
	 * 
	 * 1. when the url is an entry, clean up the url
	 * 
	 * 2. when url is in CLEAN_UP url list
	 * 
	 * @param request
	 * @return
	 */
	protected boolean shouldCleanup(HttpServletRequest request) {
		String menu = request.getParameter("menu");
		String submenu = request.getParameter("submenu");
		return StringUtils.isNotBlank(menu) && StringUtils.isNotBlank(submenu);
	}

}
